export const cache = (key, val)=>{
	if (key === 'clear') {
		window.localStorage.clear();
	} else if (val === null) {
		window.localStorage.removeItem(key);
	} else if (val) {
		window.localStorage[key] = val;
	} else {
		return window.localStorage[key];
	}
}

export function validateUrl(url){
	return /^(zaapp|http|https):\/\/.+$/.test(url)
}

export function validateEmail(email){
	return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/.test(email);
}

/*
生成guid
 */
export const guid = ()=>{
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
		return v.toString(16);
	});
}

/*
构造tree组件需要的数据结构
 */
export const genTree = (data, valueAttr="code", parentAttr='parentCode', childAttr="children", setRootValue=false)=>{
	if(!Array.isArray(data) || data.length<1) {
		console.log('构造树结构失败，data参数不合法')
		return [];
	}

	function setChild(parent, list, rootValue){
		if(setRootValue){
			parent._rootValue = rootValue;
		}

		let childList = list.filter(item=>item[parentAttr] === parent[valueAttr]);
		if(childList.length>0) {
			parent[childAttr] = childList;
			childList.forEach(childItem => setChild(childItem, list, rootValue))
		}
	}

	let rootList = data.filter(item=>!item[parentAttr]);
	rootList.forEach(rootItem=>setChild(rootItem, data, rootItem[valueAttr]))

	return rootList;
}

/*
展开树结构为平级数据
 */
export const expandTree = (treeData, childAttr="children", removeChildAndClone=true)=>{
	if(!Array.isArray(treeData) || treeData.length<1) {
		console.log('展开树结构失败，treeData参数不合法')
		return [];
	}

	let result = [];

	function expandChild(parent){
		result.push(parent);
		if(parent[childAttr]){
			parent[childAttr].forEach(item=>expandChild(item))
		}
	}

	treeData.forEach(item=>expandChild(item));

	// 移除子节点属性
	if(removeChildAndClone){
		result = result.map(item=>{
			let _item = {...item};
			delete _item[childAttr];
			return _item;
		})	}

	return result;
}
